<template>
    <div class="list">
        <div :class="['item', +message.chatfrom===1 && 'self']" v-for="(message) in messages"
             :key="message.id">
            <system-message
                    v-if="message.msgtype === 8 || message.msgtype === 9 "
                    :data="message.content"
                    @quit="quitGroup(message)"
            />
            <template v-else>
                <el-tooltip
                        placement="top-start"
                        :disabled=" message.friendwxid && message.friendwxid.indexOf('@chatroom') < 0 || message.chatfrom===1"
                        popper-class="message-tool-tip">
                    <img v-if="message.chatfrom===1" class="item-avatar" :src=" account.avatar||defaultAvatar" alt="">
                    <img v-else class="item-avatar" :src=" (isGroup?message.realFromHeadImg:chat.avatar) ||defaultAvatar" alt="">
                    <div slot="content">
                        <el-button-group>
                            <el-button @click="$emit('groupReply', message)" class="message-tool-button" type="info"
                                       size="mini">群回复
                            </el-button>
                            <el-button @click="$emit('atUser', message)" class="message-tool-button" type="info"
                                       size="mini">@他
                            </el-button>
                            <el-button v-if="isOwner" @click="$emit('deleteUser',message)" class="message-tool-button"
                                       type="info" size="mini">踢出群群
                            </el-button>
                            <el-button @click="addFriend( message)" class="message-tool-button" type="info"
                                       size="mini">加好友
                            </el-button>
                        </el-button-group>
                    </div>
                </el-tooltip>
                <div class="message-wrap">
                    <div class="item-username" v-if="isGroup && message.realFromNick">
                        {{message.realFromNick}}
                    </div>
                    <div class="status-wrap">
                        <i v-if="message.msgtype===14 && message.sendstatus===0 && typeof message.cmdid==='number' "
                           class="el-icon-success message-join"></i>
                        <i v-else-if="message.msgtype===14 && message.sendstatus===20005 && typeof message.cmdid==='number' "
                           class="el-icon-success message-join"></i>
                        <i v-else-if="message.sendstatus==-100" class="el-icon-loading message-loading"></i>
                        <el-popover
                                v-else-if="message.sendstatus!=0 && message.sendstatus!=-100 "
                                placement="top"
                                title=""
                                width="50"
                                v-model="message.popover"
                                trigger="click">
                            <p v-if="message.msgtype===14 && message.chatfrom===2">失败原因：<br/>{{message.sendstatus+':'+wechatCode[message.sendstatus]}}
                            </p>
                            <div v-else>
                                <p>失败原因：<br/>{{message.sendstatus+':'+wechatCode[message.sendstatus]}}，是否重新发送？</p>
                                <div style="text-align: right; margin: 0">
                                    <el-button size="mini" type="text" @click="message.popover = false">取消</el-button>
                                    <el-button type="primary" size="mini"
                                               @click="repeat(message),message.popover = false;">确定
                                    </el-button>
                                </div>
                            </div>

                            <i slot="reference" class="el-icon-warning message-error"></i>
                        </el-popover>
                        <el-tooltip placement="top" popper-class="message-tool-tip"
                                    :disabled="![1,2,3,4,6,10,11].includes(message.content.msgtype)">

                            <message-item @click="messageClick(message)" :reply="message"></message-item>
                            <div slot="content">
                                <el-button-group>
                                    <el-button @click="handleClipboard(message,$event)"
                                               v-if="message.content.msgtype===1" class="message-tool-button"
                                               type="info" size="mini">复制
                                    </el-button>
                                    <el-button @click="copy(message.localid,$event)"
                                               v-if="message.localid" class="message-tool-button"
                                               type="info" size="mini">复制ID
                                    </el-button>
                                    <el-button @click="revokeMsg(message)" v-if="message.chatfrom===1 && now-new Date(message.sendtime) < 1000 * 60" class="message-tool-button" type="info" size="mini">撤回</el-button>
                                    <el-button @click="scanImage(message)"
                                               v-if="message.content.msgtype===2&&message.chatfrom===2"
                                               class="message-tool-button" type="info" size="mini">识别二维码
                                    </el-button>
                                    <el-button @click="downloadFromBrowser(message)"
                                               v-if="[2,3,4,6].includes(message.content.msgtype)"
                                               class="message-tool-button" type="info" size="mini">下载
                                    </el-button>
                                </el-button-group>
                            </div>

                        </el-tooltip>
                    </div>

                </div>
                <div v-if="message.createtime" class="send-time">local:{{message.localid}} {{ formatTime(message.createtime) }}</div>
            </template>

        </div>


    </div>
</template>
<script>
    import MessageItem from '@/components/messageItem'
    import SystemMessage from '@/components/systemMessage'
    import {throttle, downloadFromBrowser} from '@/lib/utils'
    import wechatCode from '@/lib/wechat-code'
    import {mapState, mapActions, mapMutations} from 'vuex';
    import Clipboard from 'clipboard'
    import {pathOr} from 'ramda'

    export default {
        name: "message-fall",
        components: {MessageItem, SystemMessage},
        props: {
            data: {type: Array},
            chat: {},
            members: [],
            account: {}
        },
        data() {
            return {
                wechatCode,
                now:new Date()
            }
        },
        mounted(){
            this.timer = setInterval(()=>{
                this.now = new Date()
            },1000)
        },
        destroyed(){
            this.timer && clearInterval(this.timer)
        },
        computed: {
            messages() {
                return this.data
            },
            isGroup() {
                return this.chat.friendwxid.endsWith('@chatroom')
            },
            isOwner() {
                return this.chat.isfirst === 1
            }
        },
        methods: {
            ...mapActions(['wsSend']),
            ...mapMutations(['updateMessageMap']),
            deleteUser(chat) {
                const index = this.$confirm(`确定踢出 ${chat.realFromNick}?`, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(rs=>{
                    this.confirmDeleteUser(chat)
                }).catch(e=>{
                    console.log(e)
                })
            },
            confirmDeleteUser(chat) {
                const { csid,wxaccount,friendwxid,realFromWxId } = chat
                this.$api.group.removeGroupMember({
                    csId :csid,
                    accountWxId: wxaccount,
                    groupNo: friendwxid,
                    memberWxId: realFromWxId
                }).then(e=>{
                    this.$message({
                        message:'任务提交成功',
                        type:'success'
                    })
                }).catch(e=>this.$msg(e))

            },

            quitGroup(message) {
                const {csid: csId, wxaccount: wxAccount, friendwxid: groupNo} = message
                const params = {
                    csId,
                    wxAccount,
                    groupNo
                }
                this.$api.group.quitGroup(params)
                    .then(rs => {
                        this.$message({
                            type: 'success',
                            message: '任务创建成功'
                        })
                    })
                    .catch(e => {
                        this.$message({
                            type: 'error',
                            message: e
                        })
                    })
            }
            ,
            addFriend(user) {
                this.$prompt('添加群成员 ' + user.realFromNick + ' 为好友？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: '你好'
                }).then(({value}) => {
                    const applyMsg = value
                    if (applyMsg === null) return;
                    const param = {
                        memberWxId: user.realFromWxId,
                        groupNo: user.friendwxid,
                        wxAccount: user.wxaccount,
                        applyMsg,
                        opType: 3
                    }
                    this.wsSend(param)
                }).catch((e) => {
                    console.log(e)
                });

            },

            handleClipboard(item, event) {
                if (item && item.content) {
                    try {
                        const message = item
                        if (message.content) {
                            this.copy(message.content.content, event)
                        } else {
                            this.$message({
                                showClose: true,
                                message: '复制失败',
                                type: 'error'
                            });
                        }
                    } catch (error) {
                        this.$message({
                            showClose: true,
                            message: '复制失败',
                            type: 'error'
                        });
                    }
                }


            },
            copy(text, event) {
                const clipboard = new Clipboard(event.target, {
                    text: () => text
                })
                clipboard.on('success', () => {
                    this.$message({
                        showClose: true,
                        message: '复制成功',
                        type: 'success'
                    });
                    clipboard.destroy()
                })
                clipboard.on('error', () => {
                    this.$message({
                        showClose: true,
                        message: '复制失败',
                        type: 'error'
                    });
                    clipboard.destroy()
                })
                clipboard.onClick(event)
            },
            scanImage(item) {
                const {csid, msgid, id} = item;

                this.$prompt('你需要发送验证申请，等对方通过', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: '你好'
                }).then(({value}) => {
                    this.$api.chat.scanImage({chatId: id, message: value, csId: csid})
                        .then(e => {
                            this.$message({
                                type: 'success',
                                message: '发送成功'
                            });
                        }).catch(() => {
                        this.$message({
                            type: 'error',
                            message: '发送失败'
                        });
                    })

                }).catch(() => {

                });


            },
            downloadFromBrowser(message) {
                const src = pathOr('', ['content', 'src'], message)
                const data = pathOr('', ['content', 'data'], message)
                if (src || data) {
                    let loadurl
                    if(src.startsWith('http')){
                        loadurl = src
                    }else{
                        loadurl = src ? (this.config.apiUrl + src) : ('data:image/png;base64,' + data)
                    }
                    downloadFromBrowser(loadurl)
                }
            },

            repeat(message) {
                if (!this.account.isonline) {
                    return this.$message({
                        showClose: true,
                        message: '设备离线,无法发送',
                        type: 'error'
                    });
                }
                const msgId = message.msgid
                const msg = {
                    wxAccount: message.wxaccount,
                    msgId,
                    msgid: msgId,
                    friendId: message.friendwxid,
                    msgType: message.msgtype,
                    msgtype: message.msgtype,
                    opType: 1,
                    content: JSON.stringify(message.content),
                    chatfrom: 1,
                    sendstatus: -100,
                    id: message.id
                }
                this.wsSend(msg)

            },
            revokeMsg(message){
                const { csid:csId,wxaccount:wxAccount,id:chatId } = message
                const param = { csId, wxAccount, chatId }
                this.$api.chat.revokeMsg(param)
                    .then(rs=>{
                        console.log(rs)
                    })
                    .catch(e=>this.$message({ type:'error',message:e }))
                console.log(message)
            },
            messageClick(message){
                if(message.msgtype === 14){
                    const { wxaccount, msgid, friendwxid,id } = message
                    if( !wxaccount && !msgid && !friendwxid )return;
                    this.$confirm('是否加入群聊?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(() => {
                    this.$api.chat.joinGroup({ wxAccount:wxaccount,msgId:msgid,friendWxId:friendwxid,chatId:id })
                        .then(e=>{
                        this.$message({
                            type: 'success',
                            message: '任务提交成功!'
                        });
                        this.updateMessageMap({id,sendstatus:-100})
                        })
                    }).catch(() => {

                    });
                    // this.$api.chat.joinGroup()
                }
                console.log(message)
            },
        }
    }
</script>
<style scoped>
    .item {
        display: flex;
        flex-direction: row;
        margin: 8px 0;
        position: relative;
    }

    .self {
        flex-direction: row-reverse;
    }

    .item-avatar {
        flex-shrink: 0;
        width: 40px;
        height: 40px;
        margin-right: 8px;
        border-radius: 3px;
    }

    .self .item-avatar {
        margin-right: 0;
        margin-left: 8px;
    }

    .item-username {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        color: #b4b1b1;
        font-size: 12px;
        margin-bottom: 5px;
    }

    .status-wrap {
        display: flex;
        justify-content: flex-end;
        flex-direction:row-reverse;
    }
    .self .status-wrap{
        flex-direction: row;
        justify-content: flex-start;
    }
    .status-wrap .message-error {
        color: #F56C6C;
        font-size: 20px;
        margin: 10px;
    }

    .status-wrap .message-loading {
        margin: 10px;
        font-size: 20px;
        width: 20px;
        height: 20px;
        color: #666;
    }

    .status-wrap .message-join {
        margin: 10px;
        font-size: 20px;
        width: 20px;
        height: 20px;
        color: #67C23A;
    }

    .message-tool-button {
        background: #303133;
        border-color: #303133;
    }

    .send-time {
        position: absolute;
        right: 0;
        font-size: 12px;
        color: #999;
        display: none;
    }

    .self .send-time {
        left: 0;
    }

    .item:hover .send-time {
        display: block
    }
</style>
